package com.example.bookstore.security;

import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

public class CustomSessionManager extends DefaultWebSessionManager {

    /**
     * 头信息中具有sessionId
     * 请求头：Token: sessionId
     * 指定sessionId的获取方式
     */
    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        //获取请求头Token中的数据
        String sessionId = WebUtils.toHttp (request).getHeader ("Token");
        if (StringUtils.isEmpty (sessionId)){
            //如果没有携带，生成新的sessionId
            return super.getSessionId (request,response);
        }else {
            //返回sessionId
            //设置从请求头获取sessionId
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, "header");
            //设置sessionId的值
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, sessionId);
            //设置sessionId是否需要判断
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
            return sessionId;
        }
    }

}
